import { convertPathsToTableData } from '@renderer/utils/TableUtils'
import { filterPathArrsUnique } from '@renderer/utils/PathUtils'
import type { Ref } from 'vue'

export default function useTableData(
  tableData: Ref<ITableDataItem[]>,
  flag: 'file' | 'folder'
) {
  // 重置
  function handleReset() {
    tableData.value.length = 0
  }

  async function getPathList(pathList: string[]) {
    const res = await convertPathsToTableData(pathList, flag)
    tableData.value.push(...res)
  }

  // 添加文件/目录
  async function handleAdd(pathList: string[]) {
    const addTableData = await convertPathsToTableData(pathList, flag)
    // 滤重
    const res = filterPathArrsUnique(tableData.value, addTableData)

    if (res.repeatCount > 0) {
      ElMessageBox.alert(
        `已过滤 ${res.repeatCount} 个无法添加或已存在的文件`,
        '提示',
        {
          confirmButtonText: '确认',
          type: 'info'
        }
      )
    }

    if (res.uniqueData) {
      tableData.value.push(...res.uniqueData)
    }
  }

  // 删除一条 tableData 数据
  function handleRemove(fullPath: string) {
    tableData.value = tableData.value.filter(
      (item) => item.fullPath !== fullPath
    )
    ElMessage({
      message: '删除成功',
      type: 'success',
      offset: 48
    })
  }

  return {
    handleReset,
    handleAdd,
    getPathList,
    handleRemove
  }
}
